
import Util from "./Util";
import TTRecorder from "./TTRecorder";
import {GameMain} from "./GameMain";
//import {GameMain} from "./GameMain";

export enum PlatformType
{
    BROWSER = 0,
    Default = BROWSER,
    TT,
    WECHAT,
    VIVO,
    OPPO,
    ANDROID

}

//游戏平台相关的工具类
export default class Platform
{
    public static currentPlatform: PlatformType = PlatformType.Default;

    public static shareTitles: Array<string> = ["大以来大鹅抓抓抓", "大以来大鹅抓抓抓", "大以来大鹅抓抓抓"];
    public static shareDesc: Array<string> = ["大以来大鹅抓抓抓",
        "大以来大鹅抓抓抓",
        "大以来大鹅抓抓抓"];
    public static shareImgUrl: string ="";// "https://sf1-ttcdn-tos.pstatp.com/img/developer/app/tt597a2fc7c642e2e602/si8018a73~noop.image";

    //tt recorder
    public static ttRecorder: TTRecorder = null;

    public static ttVideoAdKey: string = "14hhjekpbkkadjln5h";
    public static ttBannerAdKey: string = "2kdcnjab771l1ah4td";
    public static ttInsertAdKey: string = "bk8c564ah5aa4caes0";

    public static ttInsertLoaded:boolean=false;

    public static wxVideoAdKey: string = "adunit-29d3d65649607f76";
    public static wxBannerAdKey: string = "adunit-af095cf38ac2d6ec";
    public static wxInsertAdKey: string = "adunit-a63ade8bc2294b82";

    public static oppoGamePortalKey:string="565569";
    public static oppoBannerAdKey:string="777856";
    public static oppoVideoAdKey:string="777858";
    public static gamePortalAdShowed:boolean=false;
    public static showNativeAdAfterPortal:boolean=false;
    public static showNativeAdAfterPortal2:boolean=false;

    public static oppoBottomCustomADKey:string="777859";
    public static oppoNative1Key:string="777860";
    public static oppoNative2Key:string="565509";

    public static vivoBannerAdKey:string="9e0ae94901a14eb2901b77ab3550fbea";
    public static vivoVideoAdKey:string="ad32f9ec9c124796a371a40334ec3a9f";
    public static vivoInsertAdKey:string="ac903b587b73413b8707b7d307aaee64";

    //bottom
    public static vivoBottomCustomADKey:string="00f4be88e7a14a83be3470a7902a9312";
    public static vivoNative1Key:string="9d65322196d345f2b3b9482f22a363e7";
    public static vivoNative2Key:string="e00aebbdaffe4013a9a1d799f79b8384";
    public static vivoPortalKey:string="2f3303f9db2b4326abbace629c0c10bf";
    public static vivoPortalAd=null;

    public static vivoCustomAd=null;
    public static customAdLastShowTime:number=0;

    public static ttVideoAdCallback: Function = null;
    public static ttVideoAdCloseCallback:Function=null;
    public static ttVideoAdErrorCallback:Function=null;

    public static ttRecording:boolean=false;

    public static videoAd = null;
    public static bannerAd = null;
    public static insertAd = null;

    public static wxShareFlag:boolean=false;

    public static wxImageUrl:string="";
    public static wxImageId:string="";


    public static loginUUID = "";

    //ov原生广告
    public static oppoGamePortalAd=null;
    public static oppoPortalAutoShow:boolean=false;

    public static oppoGamePortalLoaded:boolean=false;

    public static shortcutButton: any = null;

    public static decidePlatform()
    {
        Platform.currentPlatform = PlatformType.Default;
        if (cc.sys.platform === cc.sys.Platform.WECHAT_GAME)
        {
            Platform.currentPlatform = PlatformType.WECHAT;

            wx.showShareMenu({
                withShareTicket: true,
                menus: ['shareAppMessage', 'shareTimeline']
            });
            wx.onShareAppMessage(function ()
            {
                let idx: number = Util.randRangeNumber(0, Platform.shareTitles.length - 1);
                return {
                    title: Platform.shareTitles[idx],
                    imageUrlId: Platform.wxImageId,
                    imageUrl: Platform.wxImageUrl
                };
            });

            wx.onShareTimeline(() => {
                return {
                    title: '开心球球消消乐!',
                    imageUrl: '', // 图片 URL
                }
            })


            wx.onHide((res) => {
                GameMain.instance.wxOnHide();
            });

            wx.onShow((res) => {
                GameMain.instance.wxOnShow();
            });

            //创建视频广告
            Platform.createVideoAd();
            wx.cloud.init();

        } else if (cc.sys.platform === cc.sys.Platform.BYTEDANCE_MINI_GAME)
        {
            Platform.currentPlatform = PlatformType.TT;

            tt.showShareMenu();

            tt.onShareAppMessage(function ()
            {
                let idx: number = Util.randRangeNumber(0, Platform.shareTitles.length - 1);
                return {
                    title: Platform.shareTitles[idx],
                    desc: Platform.shareDesc[idx],
                    imageUrl: Platform.shareImgUrl,
                    //templateId: '这是开发者后台设置的分享素材模板id',
                    success()
                    {
                        console.log("**转发成功");
                    },
                    fail()
                    {
                        console.log("转发失败");
                    }
                };
            });

            //初始化视频recorder
            Platform.initTTRecorder();

            //创建视频广告
            Platform.createVideoAd();
        }
        else if(cc.sys.platform === cc.sys.Platform.OPPO_MINI_GAME)
        {
            Platform.currentPlatform = PlatformType.OPPO;
            /*
            if (CC_DEBUG)
            {
                 qg.setEnableDebug({
                     enableDebug: true, // true 为打开，false 为关闭
                     success: function () {
                         // 以下语句将会在 vConsole 面板输出 
                         console.log("qg.setEnableDebug success");
                     },
                     complete: function () {
                     },
                     fail: function () {
                         console.log("qg.setEnableDebug success");
                     }
                 });
            }*/

            //创建视频广告
            Platform.createVideoAd();
        }
        else if(cc.sys.platform === cc.sys.Platform.VIVO_MINI_GAME)
        {
            Platform.currentPlatform = PlatformType.VIVO;
            //创建视频广告
            //Platform.createVideoAd();
        }
        else if(cc.sys.platform===cc.sys.Platform.ANDROID)
        {
            Platform.currentPlatform=PlatformType.ANDROID;
        }

        //console.log("** XXX Platform==="+Platform.currentPlatform+"  sys="+cc.sys.platform);
    }


    //是否应该检测协议同意
    public static needAgreement():boolean
    {
        if(Platform.isOV() || Platform.isAndroid())
            return true;
        return false;
    }

    public static isDouyin():boolean
    {
        if(Platform.currentPlatform!==PlatformType.TT)
            return false;
        let sysInfo = tt.getSystemInfoSync();
        if(sysInfo.appName==="Douyin")
        {
            return true;
        }
        return false;
    }

    public static isHuoShan()
    {
        let sysInfo = tt.getSystemInfoSync();
        if(sysInfo.appName==="live_stream")
        {
            return true;
        }
        return false;
    }

    public static isOV()
    {
        if(Platform.currentPlatform===PlatformType.OPPO || Platform.currentPlatform===PlatformType.VIVO)
            return true;
        return false;
    }

    public static isAndroid()
    {
        if(Platform.currentPlatform===PlatformType.ANDROID)
            return true;
        return false;
    }

    private static initTTRecorder()
    {
        Platform.ttRecorder = new TTRecorder();
    }

    public static startRecord()
    {
        if (Platform.ttRecorder !== null)
        {
            Platform.ttRecorder.start();
            Platform.ttRecording=true;
        }
    }

    public static stopRecord(stopCB:Function=null)
    {
        if (Platform.ttRecorder !== null)
        {
            Platform.ttRecorder.stop(stopCB);
            Platform.ttRecording=false;
        }
    }

    public static shareRecord(callback:Function=null)
    {
        if (Platform.ttRecorder !== null)
        {
            let idx: number = Util.randRangeNumber(0, Platform.shareTitles.length - 1);
            Platform.ttRecorder.shareClipAdv(Platform.shareTitles[idx], Platform.shareDesc[idx], callback);
        }
    }

    public static vibrateShort()
    {

        if (GameMain.instance.gameData.vibration !== "on")
            return;
        if (Platform.currentPlatform === PlatformType.TT)
        {
            tt.vibrateShort();

        } else if (Platform.currentPlatform === PlatformType.WECHAT)
        {
            wx.vibrateShort();
        }
        else if(Platform.currentPlatform===PlatformType.OPPO)
        {
            qg.vibrateShort({ });
        }
        else if(Platform.currentPlatform===PlatformType.VIVO)
        {
            qg.vibrateShort();
        }
    }

    public static showToast(msg:string, t:number=2000)
    {
        if(Platform.currentPlatform===PlatformType.TT)
        {
            tt.showToast({
                title: msg,
                duration: t,
                success(res) {
                },
                fail(res) {
                },
            });
        }
        else if (cc.sys.platform === cc.sys.OPPO_MINI_GAME) {
            qg.showToast({
                title: msg,
                icon: 'success',
                duration: t
            });
        }
        else if (cc.sys.platform === cc.sys.VIVO_MINI_GAME) {
            qg.showToast({
                message: msg,
                duration: t
            })
        }
    }

    public static showShortcutBtn(){
        if (this.shortcutButton){
            cc.log("Platform showShortcutBtn")
            this.shortcutButton.show()
        }
    }

    public static createShortcutBtn(){
        cc.log("Platform createShortcutBtn")
        if (cc.sys.platform === cc.sys.VIVO_MINI_GAME) {
            if (!qg.createShortcutButton){
                return
            }

            var doFunc = ()=>{
                var sysInfo = qg.getSystemInfoSync()
                var button = qg.createShortcutButton({
                    type: 'image',
                    style: {
                        left: 8,
                        top: sysInfo.screenHeight/2,
                        width: 100,
                        height: 100,
                        color : "#f8f8f8"
                    }
                })

                var startHandler = (data)=> {
                    console.log(data)
                    button.destroy()
                    this.shortcutButton = null
                }

                button.onTap(startHandler)
                this.shortcutButton = button
            }

            qg.hasShortcutInstalled({
                success: function(res) {
                    // 判断图标未存在时，创建图标
                    if (res == false) {
                        doFunc()
                    }
                    else {
                    }
                },
                fail: function(err) {},
                complete: function() {}
            });
        }
    }

    public static hideShortcutBtn(){
        if (cc.sys.platform === cc.sys.VIVO_MINI_GAME) {
            if (this.shortcutButton){
                cc.log("Platform hideShortcutBtn")
                this.shortcutButton.hide()
            }
        }
    }

    //添加桌面快捷
    public static addShortcut(cb)
    {
        if(Platform.currentPlatform===PlatformType.OPPO)
        {
            qg.hasShortcutInstalled({
                success: function(res) {
                    // 判断图标未存在时，创建图标
                    if (res == false) {
                        qg.installShortcut({
                            success: function() {
                                // 执行用户创建图标奖励
                                Platform.showToast("桌面图标已创建");
                            },
                            fail: function(err) {
                                Platform.showToast("创建失败,请稍后再试");
                            },
                            complete: function() {}
                        })
                    }
                    else {
                        cb && cb()
                    }
                },
                fail: function(err) {},
                complete: function() {}
            });
        }
        else if(Platform.currentPlatform===PlatformType.VIVO)
        {
            qg.hasShortcutInstalled({
                success: (status)=> {
                    if(status)
                    {
                        cb && cb();
                        console.log('已创建');
                        //Platform.showToast("桌面图标已创建");
                    }
                    else {
                        console.log('未创建')
                        qg.installShortcut({
                            success: ()=> {
                                //Platform.showToast("桌面图标已创建");
                            }
                        });
                    }
                }
            });
        }
    }


    public static shareApp()
    {
        if (Platform.currentPlatform === PlatformType.TT)
        {
            //tt.showShareMenu();
            let idx: number = Util.randRangeNumber(0, Platform.shareTitles.length - 1);
            tt.shareAppMessage(
                {
                    title: Platform.shareTitles[idx],
                    desc: Platform.shareDesc[idx],
                    imageUrl: Platform.shareImgUrl,
                    //templateId: '这是开发者后台设置的分享素材模板id',
                    success()
                    {

                    },
                    fail()
                    {

                    }

                });

        } else if (Platform.currentPlatform === PlatformType.WECHAT)
        {
            //Platform.wxShareFlag=true;
            let idx: number = Util.randRangeNumber(0, Platform.shareTitles.length - 1);
            wx.shareAppMessage(
                {
                    title: Platform.shareTitles[idx],
                    imageUrlId: Platform.wxImageId,
                    imageUrl: Platform.wxImageUrl
                    /*
                    imageUrl: canvas.toTempFilePathSync({
                        destWidth: 500,
                        destHeight: 400
                    })*/

                });
        }

    }

    //平台登陆
    public static login()
    {
        if (Platform.currentPlatform === PlatformType.TT)
        {
            tt.login({
                success(res)
                {
                    /*
                    tt.getUserInfo({
                        success (res) {
                            console.log("用户信息: ", res.userInfo);
                            if (setUserInfo !== null) {
                                setUserInfo(res.userInfo.avatarUrl, res.userInfo.nickName)
                            }
                        },
                        fail (res) {
                            console.log("fail")
                            console.log("请求用户信息失败: ", res.errMsg)
                            if (failGetUserInfo !== null) {
                                failGetUserInfo()
                            }
                        }
                    });*/
                },
                fail(res)
                {
                    //console.log(`login调用失败`);
                }
            });
        }
    }

    //创建视频广告对象
    public static createVideoAd()
    {
        if (Platform.currentPlatform === PlatformType.TT)
        {
            Platform.videoAd = tt.createRewardedVideoAd({adUnitId: Platform.ttVideoAdKey});
            if (Platform.videoAd !== null && this.videoAd !== undefined)
            {
                Platform.videoAd.onClose(res =>
                {
                    if (res.isEnded)
                    {
                        console.log("**广告看完奖励");
                        // 给予奖励
                        if (Platform.ttVideoAdCallback !== null)
                            Platform.ttVideoAdCallback();

                    } else
                    {
                        console.log("广告没看完");
                        if(Platform.ttVideoAdCloseCallback!==null)
                            Platform.ttVideoAdCloseCallback();
                    }

                });

                Platform.videoAd.onError(res =>
                {
                    console.log("VideoAd Error code=" + res.errCode + " errMsg=" + res.errMsg);
                    if(Platform.ttVideoAdErrorCallback!==null)
                        Platform.ttVideoAdErrorCallback();
                });
            }
        }
        else if (Platform.currentPlatform === PlatformType.WECHAT)
        {
            Platform.videoAd = wx.createRewardedVideoAd({adUnitId: Platform.wxVideoAdKey});
            if (Platform.videoAd !== null && this.videoAd !== undefined)
            {
                Platform.videoAd.onClose(res =>
                {
                    if (res.isEnded)
                    {
                        console.log("**广告看完奖励");
                        // 给予奖励
                        if (Platform.ttVideoAdCallback !== null)
                            Platform.ttVideoAdCallback();

                    } else
                    {
                        console.log("广告没看完");
                        if(Platform.ttVideoAdCloseCallback!==null)
                            Platform.ttVideoAdCloseCallback();
                    }

                });

                Platform.videoAd.onError(res =>
                {
                    console.log("VideoAd Error code=" + res.errCode + " errMsg=" + res.errMsg);
                });
            }
        }
        else if (Platform.currentPlatform === PlatformType.OPPO)
        {
            Platform.videoAd = qg.createRewardedVideoAd({adUnitId: Platform.oppoVideoAdKey});

            if (Platform.videoAd !== null && Platform.videoAd !== undefined)
            {
                Platform.videoAd.onClose(res =>
                {
                    if (res.isEnded)
                    {
                        console.log("**广告看完奖励");
                        // 给予奖励
                        if (Platform.ttVideoAdCallback !== null)
                            Platform.ttVideoAdCallback();

                    } else
                    {
                        if(Platform.ttVideoAdCloseCallback!==null)
                            Platform.ttVideoAdCloseCallback();
                    }
                });

                Platform.videoAd.onLoad(()=> {
                    //console.log('激励视频加载成功')
                    Platform.videoAd.show();
                });

                Platform.videoAd.onError(res =>
                {
                    console.log("VideoAd Error code oppo=" + res.errCode + " errMsg=" + res.errMsg);
                    qg.showToast({
                        title: '请稍后再试。',
                        icon: 'loading',
                        duration: 2000
                    });
                });
            }

            /*
            if(Platform.videoAd!==null)
                Platform.videoAd.load();*/
        }
        else if (Platform.currentPlatform === PlatformType.VIVO)
        {
            Platform.videoAd = qg.createRewardedVideoAd({posId: Platform.vivoVideoAdKey});

            /*
            if(Platform.videoAd!==null)
                Platform.videoAd.load();

             */
            if (Platform.videoAd !== null && Platform.videoAd !== undefined)
            {
                Platform.videoAd.onClose(res =>
                {
                    if (res.isEnded)
                    {
                        console.log("**广告看完奖励");
                        // 给予奖励
                        if (Platform.ttVideoAdCallback !== null)
                            Platform.ttVideoAdCallback();

                    } else
                    {
                        console.log("广告没看完");
                    }

                });

                Platform.videoAd.onError(res =>
                {
                    console.log("VideoAd Error code oppo=" + res.errCode + " errMsg=" + res.errMsg);
                    //console.log("VideoAd Error code=OPPO");
                });
            }
        }
    }


    //播放视频广告
    public static playVideoAd(callback: Function = null, closeCallback:Function=null,errorCallback:Function=null)
    {

        if (Platform.currentPlatform === PlatformType.TT)
        {
            if (Platform.videoAd === null || Platform.videoAd === undefined)
                Platform.videoAd = tt.createRewardedVideoAd({adUnitId: Platform.ttVideoAdKey});
            Platform.ttVideoAdCallback = callback;
            Platform.ttVideoAdCloseCallback=closeCallback;
            Platform.ttVideoAdErrorCallback=errorCallback;
            Platform.videoAd.show()
                .then(() =>
                {
                    console.log('广告显示成功');
                })
                .catch(err =>
                {
                    console.log('广告组件出现问题', err);
                    // 可以手动加载一次
                    Platform.videoAd.load()
                        .then(() =>
                        {
                            console.log('手动加载成功并播放');
                            Platform.videoAd.show();
                        });
                });
        }
        else if (Platform.currentPlatform === PlatformType.WECHAT)
        {
            if (Platform.videoAd === null || Platform.videoAd === undefined)
                Platform.videoAd = wx.createRewardedVideoAd({adUnitId: Platform.wxVideoAdKey});
            Platform.ttVideoAdCallback = callback;
            Platform.ttVideoAdCloseCallback=closeCallback;
            this.videoAd.show()
                .then(() =>
                {
                    console.log('广告显示成功');
                })
                .catch(err =>
                {
                    console.log('广告组件出现问题', err);
                    // 可以手动加载一次
                    Platform.videoAd.load()
                        .then(() =>
                        {
                            console.log('手动加载成功并播放');

                        });
                });
        }
        else if(Platform.currentPlatform===PlatformType.OPPO)
        {
            if (Platform.videoAd === null || Platform.videoAd === undefined)
                Platform.videoAd = qg.createRewardedVideoAd({adUnitId: Platform.oppoVideoAdKey});
            Platform.ttVideoAdCallback = callback;
            Platform.ttVideoAdCloseCallback=closeCallback;
            Platform.ttVideoAdErrorCallback=errorCallback;

            Platform.videoAd.load();
        }
        else if(Platform.currentPlatform===PlatformType.VIVO)
        {
            Platform.ttVideoAdCallback = callback;
            Platform.ttVideoAdCloseCallback=closeCallback;
            Platform.ttVideoAdErrorCallback=errorCallback;
            if (Platform.videoAd === null || Platform.videoAd === undefined)
            {
                Platform.videoAd = qg.createRewardedVideoAd({posId: Platform.vivoVideoAdKey});

                Platform.videoAd.onLoad((res)=>{
                    Platform.videoAd.show();
                });

                Platform.videoAd.onError((err)=>{
                    //加载失败, 给予提示
                });

                Platform.videoAd.onClose(res =>
                {
                    if (res.isEnded)
                    {
                        console.log("**广告看完奖励");
                        // 给予奖励
                        if (Platform.ttVideoAdCallback !== null)
                            Platform.ttVideoAdCallback();

                    } else
                    {
                        console.log("*** vivo广告没看完2");
                        if(Platform.ttVideoAdCloseCallback!==null)
                            Platform.ttVideoAdCloseCallback();

                    }

                });
            }
            else
            {
                Platform.videoAd.load();
            }
        }
        else if(Platform.isAndroid())
        {
            GameMain.instance.showNativeVedio();
        }
        else if (Platform.currentPlatform === PlatformType.Default){
            callback()
        }
    }

    public static createInsertAd()
    {
        if(Platform.currentPlatform===PlatformType.TT)
        {

            if (Platform.insertAd !== null)
            {
                Platform.insertAd.show();
                return
            }

            Platform.insertAd = tt.createInterstitialAd({
                adUnitId: Platform.ttInsertAdKey,
            });
            Platform.insertAd.show().catch((err) => {
                    console.log(err);
            });

        }
        else if(Platform.currentPlatform===PlatformType.WECHAT)
        {

            if (Platform.insertAd !== null)
                {
                    Platform.insertAd
                    .load()
                    .then(() => {
                        Platform.insertAd.show();
                    })
                    .catch((err) => {
                        console.log(err);
                    });
                    return
                }

            Platform.insertAd = wx.createInterstitialAd({
                adUnitId: Platform.wxInsertAdKey
            });

            if (Platform.insertAd) {
                Platform.customAdLastShowTime=Date.now();
                Platform.insertAd.show();
            }
        }
    }

    public static destroyInsertAd()
    {
        if (Platform.currentPlatform === PlatformType.TT)
        {
            if (Platform.insertAd !== null)
            {
                Platform.insertAd.destroy();
                Platform.insertAd = null;
            }
        }
    }


    //创建BannerAd
    public static createBannerAd()
    {
        if (Platform.currentPlatform === PlatformType.TT)
        {
            if(Platform.isHuoShan())
                return;

            if (Platform.bannerAd !== null)
            {
                Platform.bannerAd.destroy();
                Platform.bannerAd = null;
            }

            let targetBannerWidth:number=200;


            let sysInfo = tt.getSystemInfoSync();

            Platform.bannerAd = tt.createBannerAd({
                adUnitId: Platform.ttBannerAdKey,
                style: {
                    width: targetBannerWidth,
                    top: sysInfo.windowHeight - targetBannerWidth*9/16
                }
            });
            Platform.bannerAd.style.left=(sysInfo.windowWidth - targetBannerWidth) * 0.5;

            Platform.bannerAd.onLoad(()=>{
                Platform.bannerAd.show();
            });

            Platform.bannerAd.onResize(size => {
                // good
                console.log("** BannerResize w="+size.width+" h="+size.height);
                Platform.bannerAd.style.top =sysInfo.windowHeight - size.height;
                Platform.bannerAd.style.left = (sysInfo.windowWidth - size.width) / 2;
            });
        }
        else if(Platform.currentPlatform===PlatformType.WECHAT)
        {

            if (Platform.bannerAd !== null)
            {
                Platform.bannerAd.destroy();
                Platform.bannerAd = null;
            }
            let targetBannerWidth:number=200;

            let sysInfo = wx.getSystemInfoSync();

            Platform.bannerAd = wx.createBannerAd({
                adUnitId: Platform.wxBannerAdKey,
                style: {
                    width: targetBannerWidth,
                    left: (sysInfo.windowWidth - targetBannerWidth) * 0.5,
                    top: sysInfo.windowHeight - targetBannerWidth*9/16
                }
            });
            Platform.bannerAd.style.left=(sysInfo.windowWidth - targetBannerWidth) * 0.5;

            Platform.bannerAd.show();

            Platform.bannerAd.onResize(size => {
                // good
                console.log(size.width, size.height);
                Platform.bannerAd.style.top =sysInfo.windowHeight - size.height;
                Platform.bannerAd.style.left = (sysInfo.windowWidth - size.width) / 2;
            });


            Platform.bannerAd.show();
        }
        else if(Platform.currentPlatform===PlatformType.OPPO)
        {
            if(Platform.bannerAd!==null)
            {
                Platform.bannerAd.destroy();
                Platform.bannerAd = null;
            }
            console.log("** OPPO create Banner");
            Platform.bannerAd  = qg.createBannerAd({
                adUnitId: Platform.oppoBannerAdKey,
                /*
                style: {
                    top: 300,
                    left: 0,
                    width: 400,
                    height: 200
                }*/
            });
            Platform.bannerAd.onLoad(()=>{
            });
            Platform.bannerAd.onError((err)=>{
            });
            Platform.bannerAd.onHide(()=>{
                GameMain.instance.report("bcls");
                /*
                if(GameMain.instance.sTime)
                {
                    Platform.createOVCustomBottomAD();
                }*/
            });
            Platform.bannerAd.show();
        }
        else if(Platform.currentPlatform===PlatformType.VIVO)
        {
            if(Platform.bannerAd!==null)
            {
                Platform.bannerAd.destroy();
                Platform.bannerAd = null;
            }

            Platform.bannerAd  = qg.createBannerAd({
                posId: Platform.vivoBannerAdKey,
                /*
                style: {
                    top: 300,
                    left: 0,
                    width: 400,
                    height: 200
                }*/
            });
            Platform.bannerAd.onLoad(()=>{
                console.log("**** vivo Banner onLoad");
            });
            Platform.bannerAd.onError((err)=>{

            });

            Platform.bannerAd.onClose(()=>{
                Platform.createOVCustomBottomAD();
            });
            Platform.bannerAd.show();
        }
    }

    public static hideBannerAd()
    {
        if (Platform.currentPlatform === PlatformType.TT)
        {
            if (Platform.bannerAd !== null)
                Platform.bannerAd.hide();
        }
        else if(Platform.currentPlatform===PlatformType.WECHAT)
        {
            if (Platform.bannerAd !== null)
                Platform.bannerAd.hide();
        }
        else if(Platform.currentPlatform===PlatformType.OPPO)
        {
            if (Platform.bannerAd !== null)
                Platform.bannerAd.hide();
        }
        else if(Platform.currentPlatform===PlatformType.VIVO)
        {
            if (Platform.bannerAd !== null)
                Platform.bannerAd.hide();
        }
    }

    public static showBannerAd()
    {
        if (Platform.currentPlatform === PlatformType.TT)
        {
            if (Platform.bannerAd !== null)
                Platform.bannerAd.show();
        }
    }

    public static destroyBannerAd()
    {
        if (Platform.currentPlatform === PlatformType.TT)
        {
            if(Platform.isHuoShan())
                return;
            if (Platform.bannerAd !== null)
            {
                Platform.bannerAd.destroy();
                Platform.bannerAd = null;
            }
        }
        else if (Platform.currentPlatform === PlatformType.WECHAT)
        {
            if (Platform.bannerAd !== null)
            {
                Platform.bannerAd.destroy();
                Platform.bannerAd = null;
            }
        }
        else if(Platform.currentPlatform===PlatformType.OPPO)
        {
            if (Platform.bannerAd !== null)
            {
                Platform.bannerAd.destroy();
                Platform.bannerAd = null;
            }
        }
        else if(Platform.currentPlatform===PlatformType.VIVO)
        {
            if (Platform.bannerAd !== null)
            {
                Platform.bannerAd.destroy();
                Platform.bannerAd = null;
            }
        }
    }

    public static createOVCustomBottomAD()
    {
        Platform.destroyBannerAd();
        Platform.destroyOVCustomAd();
        let adKey:string="";
        if(Platform.currentPlatform===PlatformType.VIVO)
        {
            adKey=Platform.vivoBottomCustomADKey;
        }
        else if(Platform.currentPlatform===PlatformType.OPPO)
        {
            adKey=Platform.oppoBottomCustomADKey;
        }
        if(qg.createCustomAd)
        {
            if(Platform.currentPlatform===PlatformType.VIVO)
            {
                Platform.vivoCustomAd = qg.createCustomAd({
                    posId: adKey,
                    style: {width: 750}
                });

                Platform.vivoCustomAd.onError((err) =>
                {
                    Platform.createBannerAd();
                });

                Platform.vivoCustomAd.onClose(()=>{
                    Platform.createBannerAd();
                });

                Platform.vivoCustomAd.show().then(() =>
                {
                    //console.log("** customAd showed");
                    Platform.customAdLastShowTime=Date.now();
                }).catch((err) =>
                {
                    //console.log("customad 展示失败", JSON.stringify(err));
                });
            }
            else if(Platform.currentPlatform===PlatformType.OPPO)
            {
                Platform.vivoCustomAd= qg.createCustomAd({
                    adUnitId: adKey,
                    style: {width: 750}
                });

                Platform.vivoCustomAd.onError((err)=>{
                    Platform.createBannerAd();
                });
                Platform.vivoCustomAd.onHide(()=>{
                    GameMain.instance.report("bccls");
                    /*
                    if(GameMain.instance.sTime)
                    {
                        Platform.createBannerAd();
                    }*/
                });

                Platform.vivoCustomAd.show().then(() =>
                {
                    //console.log("** customAd showed");
                    Platform.customAdLastShowTime=Date.now();
                }).catch((err) =>
                {
                    console.log("customad 展示失败", JSON.stringify(err));
                });
            }
        }
    }

    public static createOVCustomAd(errCB:Function=null)
    {
        Platform.destroyBannerAd();
        Platform.destroyOVCustomAd();
        let adKey:string="";
        if(Platform.currentPlatform===PlatformType.VIVO)
        {
            adKey=Platform.vivoNative1Key;
        }
        else if(Platform.currentPlatform===PlatformType.OPPO)
        {
            adKey=Platform.oppoNative1Key;
        }
        if(qg.createCustomAd)
        {
            if(Platform.currentPlatform===PlatformType.VIVO)
            {
                Platform.vivoCustomAd = qg.createCustomAd({
                    posId: adKey,
                    style: {top: 735}
                });

                Platform.vivoCustomAd.onError((err) =>
                {
                    if(errCB!==null)
                        errCB();
                });

                Platform.vivoCustomAd.onClose(()=>{
                   Platform.destroyBannerAd();
                   Platform.createOVCustomBottomAD();
                });

                Platform.vivoCustomAd.show().then(() =>
                {
                    //console.log("** customAd showed");
                }).catch((err) =>
                {
                    //console.log("customad 展示失败", JSON.stringify(err));
                });
            }
            else if(Platform.currentPlatform===PlatformType.OPPO)
            {
                Platform.vivoCustomAd= qg.createCustomAd({
                    adUnitId: adKey,
                    style: {top: 735}
                });


                Platform.vivoCustomAd.onHide(()=>{
                    GameMain.instance.report("ccls");
                    /*
                    if(GameMain.instance.sTime)
                    {
                        Platform.destroyBannerAd();
                        Platform.createOVCustomBottomAD();
                    }*/
                });

                Platform.vivoCustomAd.show().then(() =>
                {
                    //console.log("** customAd showed");
                }).catch((err) =>
                {
                    console.log("customad 展示失败", JSON.stringify(err));
                });
            }
        }
    }

    public static destroyOVCustomAd()
    {
        if(Platform.vivoCustomAd!==null)
        {
            Platform.vivoCustomAd.destroy();
            Platform.vivoCustomAd=null;
        }
    }

    public static createGamePortalAd()
    {
        //如果已经存在先销毁
        if(Platform.oppoGamePortalAd!==null)
        {
            Platform.oppoGamePortalAd.destroy();
            Platform.oppoGamePortalAd=null;
        }

        if(qg.getSystemInfoSync().platformVersionCode >= 1076)
        {
            Platform.oppoGamePortalAd=qg.createGamePortalAd({
                adUnitId:Platform.oppoGamePortalKey
            });

            Platform.oppoGamePortalAd.onLoad(()=>{
                console.log("** oppoGamePortal loaded");
                Platform.oppoGamePortalLoaded=true;
                if(Platform.oppoPortalAutoShow)
                {
                    Platform.oppoGamePortalAd.show();
                    Platform.oppoPortalAutoShow=false;
                    Platform.gamePortalAdShowed=true;
                }
            });

            Platform.oppoGamePortalAd.onClose(()=>{
                Platform.oppoGamePortalLoaded=false;
                Platform.gamePortalAdShowed=false;
            });

            Platform.oppoGamePortalAd.onError((err)=> {
                //console.log("** oppoGamePortalAd Err="+JSON.stringify(err));
                if(Platform.oppoPortalAutoShow)
                {
                    qg.showToast({
                        title: '暂时无广告,请稍后再试。',
                        icon: 'success',
                        duration: 2000
                    });
                }
            });

            //Platform.oppoGamePortalAd.load();
        }
        else
        {
            console.log('快应用平台版本号低于1076，暂不支持互推盒子相关 API')
        }
    }

    public static showGamePortalAd()
    {
        if(Platform.oppoGamePortalAd===null)
            return;
        if(Platform.oppoGamePortalLoaded)
        {
            Platform.oppoGamePortalAd.show().then(() => {
                Platform.gamePortalAdShowed=true;
            }).catch((error) => {
                console.log('showGamePortalAd fail with:' + error.errCode + ',' + error.errMsg);
            });
        }
        else
        {
            Platform.oppoPortalAutoShow=true;
            Platform.oppoGamePortalAd.load();
        }
    }

    public static showVivoPortalAd()
    {
        if (qg.createBoxPortalAd) {
            Platform.vivoPortalAd = qg.createBoxPortalAd({
                posId: Platform.vivoPortalKey,
                image: '',
                marginTop: 750
            });

            Platform.vivoPortalAd.onError((err)=>{
                //console.log("盒子九宫格广告加载失败", err);
                //GameMain.instance.debugLabel.string="互推盒Err";
            });
            Platform.vivoPortalAd.onClose(()=>{
                console.log('close');
                if (Platform.vivoPortalAd.isDestroyed) {
                    return;
                }
                // 当九宫格关闭之后，再次展示Icon
                Platform.vivoPortalAd.show();
            });
            // 广告数据加载成功后展示
            Platform.vivoPortalAd.show().then(()=>{
                //console.log('show success');
                //GameMain.instance.debugLabel.string="互推盒子show success";
            });
        } else {
            //console.log('暂不支持互推盒子相关 API')
            //GameMain.instance.debugLabel.string="不支持互推盒子";
        }
    }

    public static reportLevelPass(levelId:number)
    {
        if (Platform.currentPlatform === PlatformType.TT && cc.sys.platform===cc.sys.BYTEDANCE_MINI_GAME)
        {
            tt.reportAnalytics('level', {
                lid: levelId
            });
        }
    }

}
